package com.ssm.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.nacos.common.utils.StringUtils;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.ssm.gateway.entity.AuthPermission;
import com.ssm.gateway.entity.AuthRole;
import com.ssm.gateway.redis.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展(只有进行检验用户角色、权限时才会调用具体方法)
 */
@Component
@Log4j2
public class StpInterfaceImpl implements StpInterface {
    @Resource
    private RedisUtil redisUtil;

    private String authPermissionPrefix = "auth.permission";  //权限key
    private String authRolePrefix = "auth.role";  //角色key


    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的权限列表
        return getAuth(loginId.toString(), authPermissionPrefix);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的角色列表
        return getAuth(loginId.toString(), authRolePrefix);
    }

    private List<String> getAuth(String loginId, String prefix) {
        String authKey = redisUtil.buildKey(prefix, loginId);
        String authValue = redisUtil.get(authKey);

        if(StringUtils.isBlank(authValue)) {
            return Collections.emptyList();
        }
        List<String> authList = new LinkedList<>();
        if(authPermissionPrefix.equals(prefix)) { //权限校验，返回权限对象集合
            List<AuthPermission> authPermissions = new Gson().fromJson(authValue, new TypeToken<List<AuthPermission>>() {}.getType());
            authList = authPermissions.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        } else if(authRolePrefix.equals(prefix)) {
            List<AuthRole> authPermissions = new Gson().fromJson(authValue, new TypeToken<List<AuthRole>>() {}.getType());
            authList = authPermissions.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());
        }
        log.info("hhh:{}", "111");
        return authList;
    }
}
